import React, { useState, useEffect } from 'react';
import { Layout, Menu, Input, Button, Card, Row, Col, Typography, Space, MenuProps, message } from 'antd';
import {
  UserOutlined,
  FormOutlined,
  CheckSquareOutlined,
  PlusOutlined,
  TeamOutlined,
  CloseOutlined,
} from '@ant-design/icons';
import styled from 'styled-components';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';

const { Header, Sider, Content } = Layout;
const { Title, Text } = Typography;
const { Search } = Input;

//布局结构
const StyledLayout = styled(Layout)`
  min-height: 100vh;
`;

const StyledHeader = styled(Header)`
  background: #fff;
  padding: 0 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
`;

const StyledContent = styled(Content)`
  margin: 24px;
  padding: 24px;
  background: #fff;
  min-height: 280px;
  border-radius: 8px;
`;

const Main: React.FC = () => {
  const navigate = useNavigate();
  const [inviteCode, setInviteCode] = useState('');
  const [selectedKey, setSelectedKey] = useState('1');
  const [myVotes, setMyVotes] = useState<any[]>([]);
  const [myJoinedVotes, setMyJoinedVotes] = useState<any[]>([]);
  const [userInfo, setUserInfo] = useState<any>(null);
  const [userAddress, setUserAddress] = useState<string | null>(null);

  
  const handleCreateVote = () => {
    navigate('/create-vote');
  };

  const handleJoinVote = async (value: string) => {
    const code = value.replace(/\s/g, '');
    if (!code || code.length !== 16) {
      message.warning('请输入有效的邀请码');
      return;
    }
    try {
      const res = await axios.get(`/api/vote/by-invite/${code}`);
      if (res.data.success && res.data.data.voteId) {
        navigate(`/vote/${res.data.data.voteId}`);
      } else {
        message.error('邀请码无效或已过期');
      }
    } catch (err) {
      message.error('邀请码无效或已过期');
    }
  };

  const handleMenuSelect: MenuProps['onSelect'] = ({ key }: { key: string }) => {
    setSelectedKey(key);
  };

  const handleLogout = () => {
    localStorage.removeItem('token');
    navigate('/');
  };

  const renderContent = () => {
    switch (selectedKey) {
      case '1':
        return (
          <div>
            <Title level={4}>参与投票</Title>
            <Row gutter={[16, 16]} style={{ marginTop: 24 }}>
              <Col span={24}>
                <Card>
                  <Space direction="vertical" size="large" style={{ width: '100%' }}>
                    <div>
                      <Text strong>输入投票邀请码：</Text>
                      <Search
                        placeholder="请输入投票邀请码"
                        enterButton="参与投票"
                        size="large"
                        onSearch={handleJoinVote}
                        style={{ marginTop: 8 }}
                      />
                    </div>
                    <Button 
                      type="primary" 
                      icon={<PlusOutlined />} 
                      size="large"
                      onClick={handleCreateVote}
                    >
                      创建新投票
                    </Button>
                  </Space>
                </Card>
              </Col>
            </Row>
          </div>
        );
      case '2':
        return (
          <div>
            <Title level={4}>我参与的投票</Title>
            <div style={{ marginTop: 24 }}>
              {myJoinedVotes.length === 0 ? (
                <Card>
                <Text type="secondary">暂无参与的投票</Text>
                </Card>
              ) : (
                <Row gutter={[16, 16]}>
                  {myJoinedVotes.map(vote => (
                    <Col span={8} key={vote._id}>
                      <Card>
                        <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                          <Title level={5} style={{ margin: 0 }}>{vote.voteName}</Title>
                          <Text>候选人数：{vote.candidates.length}</Text>
                          <Button 
                            type="primary" 
                            block
                            onClick={() => navigate(`/vote/${vote._id}`)}
                          >
                            进入投票
                          </Button>
                        </Space>
                      </Card>
                    </Col>
                  ))}
                </Row>
              )}
            </div>
          </div>
        );
      case '3':
        return (
          <div>
            <Title level={4}>我创建的投票</Title>
            <div style={{ marginTop: 24 }}>
              {myVotes.length === 0 ? (
                <Card>
                <Text type="secondary">暂无创建的投票</Text>
                </Card>
              ) : (
                <Row gutter={[16, 16]}>
                  {myVotes.map(vote => (
                    <Col span={8} key={vote._id}>
                      <Card>
                        <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                          <Title level={5} style={{ margin: 0 }}>{vote.voteName}</Title>
                          <Text>候选人数：{vote.candidates.length}</Text>
                          <Button 
                            type="primary" 
                            block
                            onClick={() => navigate(`/vote/${vote._id}`)}
                          >
                            进入投票
                          </Button>
                        </Space>
                      </Card>
                    </Col>
                  ))}
                </Row>
              )}
            </div>
          </div>
        );
      case '4':
        return (
          <div>
            <Title level={4}>个人信息</Title>
            <Row gutter={[16, 16]} style={{ marginTop: 24 }}>
              <Col span={24}>
                <Card>
                  <Space direction="vertical" size="large">
                    <div>
                      <Text strong>用户名：</Text>
                      <Text>{userInfo?.username || '未获取'}</Text>
                    </div>
                    <div>
                      <Text strong>钱包地址：</Text>
                      <Text>{userInfo?.walletAddress || '未绑定'}</Text>
                    </div>
                  </Space>
                </Card>
              </Col>
            </Row>
          </div>
        );
      default:
        return null;
    }
  };

  // 获取钱包地址
  useEffect(() => {
    if ((window as any).ethereum && (window as any).ethereum.selectedAddress) {
      const address = (window as any).ethereum.selectedAddress.toLowerCase();
      console.log('当前钱包地址:', address);
      setUserAddress(address);
    }
  }, []);

  // 获取我参与的投票
  useEffect(() => {
    if (!userAddress) {
      console.log('未检测到钱包地址，跳过获取参与投票');
      return;
    }
    
    console.log('开始获取参与投票，地址:', userAddress);
    axios.get(`/api/vote/my-joined?address=${userAddress}`)
      .then(res => {
        console.log('获取参与投票响应:', res.data);
        if (res.data.success) {
          setMyJoinedVotes(res.data.data);
        }
      })
      .catch(err => {
        console.error('获取参与投票失败:', err);
      });
  }, [userAddress]);

  //获取我创建的投票
  useEffect(() => {
   
    const token = localStorage.getItem('token');
    axios.get('/api/vote/my-created', {
      headers: { Authorization: `Bearer ${token}` }
    }).then(res => {
      if (res.data.success) {
        setMyVotes(res.data.data); 
      }
    });
  }, []);

  useEffect(() => {
    // 获取个人信息
    const token = localStorage.getItem('token');
    axios.get('/api/user/me', {
      headers: { Authorization: `Bearer ${token}` }
    }).then(res => {
      if (res.data.success) {
        setUserInfo(res.data.data);
      }
    });
  }, []);

  return (
    <StyledLayout>
      <StyledHeader>
        <Title level={3} style={{ margin: 0 }}>区块链投票系统</Title>
        <Space>
          <Button type="text" icon={<UserOutlined />} onClick={handleLogout}>退出登录</Button>
        </Space>
      </StyledHeader>
      <Layout>
        <Sider width={200} theme="light">
          {/* 菜单栏 */}
          <Menu
            mode="inline"
            selectedKeys={[selectedKey]}
            style={{ height: '100%', borderRight: 0 }}
            onSelect={handleMenuSelect}
            items={[
              {
                key: '1',
                icon: <TeamOutlined />,
                label: '参与投票',
              },
              {
                key: '2',
                icon: <CheckSquareOutlined />,
                label: '我参与的投票',
              },
              {
                key: '3',
                icon: <FormOutlined />,
                label: '我创建的投票',
              },
              {
                key: '4',
                icon: <UserOutlined />,
                label: '个人信息',
              },
            ]}
          />
        </Sider>
        <Layout style={{ padding: '0 24px 24px' }}>
          <StyledContent>
            {renderContent()}
          </StyledContent>
        </Layout>
      </Layout>
    </StyledLayout>
  );
};

export default Main; 